#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

#include "../shared/packet.h"
#include "../libcomm.h"

#ifdef WIN32
#include <winsock2.h>
#else
#include <netinet/in.h>
#endif


int create_packet(BYTE **buffer,WORD wMCmd,WORD wSCmd,void *data,WORD wDataSize)
{
   WRITE_DEBUG("enter craetea_apcket,wMCMD:%d,wSCMD:%d,wDataSize:%d",wMCmd,wSCmd,wDataSize);

   CMD_NO cmdNo;
   int packlen = sizeof(cmdNo) + wDataSize;
   *buffer = (BYTE *)calloc(1,packlen+sizeof(int));
   if (NULL == *buffer) return 0;

   cmdNo.wMNo = wMCmd;
   cmdNo.wSNo = wSCmd;
   memcpy(*buffer,(void *)&packlen,sizeof(int));
   memcpy(*buffer+sizeof(int),(void *)&cmdNo,sizeof(cmdNo));
   if (wDataSize>0)
      memcpy(*buffer+sizeof(int)+sizeof(cmdNo),data,wDataSize);

   
   return packlen + sizeof(int) ;

}

int send_packet(WORD wSocket,void *data,WORD wDataSize)
{
   int want = wDataSize ;
   int sended = 0;

   while (sended<want){
      int n = send(wSocket,data+sended,want - sended,0);
      if (n>0) sended += n;
      else if (n<0 && (errno == EAGAIN || errno == EINTR)) {
       continue; 
      }
      else{
       WRITE_DEBUG("send n=%d error!",n); 
       break;
      }  
   }

   if (NULL != data){
     free(data);
     data = NULL;
   }

   WRITE_DEBUG("[%d] %d bytes sended",wSocket,sended);

   return sended;
}


